package cn.hhit.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import cn.dms.equipment.model.Equipment;
import cn.dms.system.model.Department;
import cn.hhit.common.pagination.Page;
import cn.hhit.common.util.Employee;
import cn.hhit.common.util.ExcelHelper;
import cn.hhit.common.util.HssfExcelHelper;
import cn.hhit.common.util.JxlExcelHelper;
import cn.hhit.common.util.StringUtil;
import cn.hhit.school.model.PlanCourseModel;
import cn.hhit.school.service.PlanCourseService;
import cn.hhit.system.service.PermissionService;

/*
 * 继承ActionSupport，并提供公共方法。所有Action继承此类
 */
public class CommonAction<M extends java.io.Serializable> extends ActionSupport implements ServletResponseAware, ServletRequestAware {

	private static final long serialVersionUID = 1L;

	@Autowired
	@Qualifier("PermissionService")
	public PermissionService permissionService;

	@Autowired
	@Qualifier("PlanCourseService")
	public PlanCourseService planCourseService;

	public HttpServletResponse response;
	public HttpServletRequest request;
	public int page;
	public int limit;
	public Map<String, Object> session = ActionContext.getContext().getSession();

	public String fname;
	public String fvalue;
	public Integer n1;
	public String s1;
	public String s2;
	public int[] delIds;
	public String instantClass;
	public boolean query;
	public String queryField;
	public String queryValue;

	public File file;
	public String fileFileName; // 文件名称
	private String fileContentType; // 文件类型
	public String overdepartment;

	public Department department;// 跨学院权限

	public static String getPrettyNumber(float number) {
		String nums = new DecimalFormat("0.00").format(number);
		return nums.replaceAll("0*$", "").replaceAll("[.]$", "");
	}

	/*
	 * 统一删除方法
	 */
	public void delRecords() {
		if (delIds != null) {
			for (int i = 0; i < delIds.length; i++) {
				permissionService.delRecordsByParams(" from " + instantClass + " where id=?", delIds[i]);
			}
		}
		writeResultToClient(response, true);
	}

	public static void writeStringToClient(HttpServletResponse response, String lstrJson, boolean result) {
		try {
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			response.getOutputStream().write(lstrJson.getBytes("utf-8"));
			response.getOutputStream().close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void writePageListToClient(HttpServletResponse response, Page<?> page) {
		String json = JSON.toJSONString(page.getItems());
		json = "{" + "\"res\":" + json + ",\"totalCount\":" + page.getContext().getTotal() + "}";
		writeStringToClient(response, json, true);
	}

	public static void writeObjectToClient(HttpServletResponse response, Object fobjValue, boolean result) {
		String lstrJson = JSON.toJSONString(fobjValue);
		if (result) {
			lstrJson = "{\"success\":true,\"result\":" + lstrJson + "}";
		}
		writeStringToClient(response, lstrJson, result);
	}

	public static void writeListToClient(HttpServletResponse response, List<?> list, boolean result) {
		String json = JSON.toJSONString(list);
		json = "{success:" + result + ",\"res\":" + json + "}";
		writeStringToClient(response, json, result);
	}

	public static void writeResultToClient(HttpServletResponse response, boolean result) {
		writeStringToClient(response, "{success:" + result + "}", result);
	}

	/*
	 * 注释部分可用于文件上传，UploadFile主要用于Excel上传并解析
	 */
	// String uploadPath =
	// ServletActionContext.getServletContext().getRealPath("/upload");
	// File savefile = new File(new File(uploadPath), fileFileName);
	// if (!savefile.getParentFile().exists()) {
	// savefile.getParentFile().mkdirs();
	// }
	// try {
	// FileUtils.copyFile(file, savefile);
	// } catch (IOException e) {
	// System.out.println("保存文件失败");
	// writeStringToClient(response, "{success:false,message:'保存文件失败'}",
	// false);
	// return;
	// }

	// InputStream is = new FileInputStream(uploadPath + "/" +
	// fileFileName);
	// Workbook rwb = Workbook.getWorkbook(is);
	public void uploadFile() throws Exception {
		if (file == null) {
			writeStringToClient(response, "{success:false,message:'服务端未收到文件'}", false);
			return;
		}

		String[] fieldNames = new String[] { "kcdm", "kcmc", "xf", "zxs", "llxs", "syxs", "kcxz", "sjhj", "department", "kcssx", "syhjbj", "kknf", "qtxf", "zkhxf" };
		ExcelHelper eh = HssfExcelHelper.getInstance(file);
		List<PlanCourseModel> courselist = eh.readExcel(PlanCourseModel.class, fieldNames, true);
		for (PlanCourseModel pcm : courselist) {
			if ("大类教育阶段".equals(pcm.getJd())) {
				pcm.setPid(-1);
			}
			pcm.setCindex(new Date());
			pcm.setState(2);
			if (!"".equals(StringUtil.parseNULLtoString(pcm.getKcdm()))) {
				if (planCourseService.getUnique(" where kcdm=?", pcm.getKcdm()) == null) {
					planCourseService.saveOrUpdate(pcm);
				}
			} else {
				planCourseService.saveOrUpdate(pcm);
			}
		}
		writeStringToClient(response, "{success:true,message:'文件上传并导入成功',fileName:'" + fileFileName + "'}", true);
	}

	public void uploadFileIO() {
		if (file == null) {
			writeStringToClient(response, "{success:false,message:'服务端未收到文件'}", false);
			return;
		}
		InputStream is = null;
		OutputStream os = null;
		// 基于myFile创建一个文件输入流
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			is = null;
			System.out.println("创建文件失败");
			writeStringToClient(response, "{success:false,message:'创建文件失败'}", false);
			return;
		}
		// 设置上传文件目录
		String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload");
		System.out.println(uploadPath);
		// 设置目标文件
		File savefile = new File(uploadPath, this.getFileFileName());
		if (!savefile.getParentFile().exists()) {
			savefile.getParentFile().mkdirs();
		}
		// 创建一个输出流
		try {
			os = new FileOutputStream(savefile);
		} catch (FileNotFoundException e) {
			os = null;
			System.out.println("创建输出流失败");
			writeStringToClient(response, "{success:false,message:'创建输出流失败'}", false);
		}
		// 设置缓存
		byte[] buffer = new byte[1024];
		int length = 0;
		// 读取文件输出到toFile文件中
		try {
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
		} catch (IOException e) {
			System.out.println("读取文件失败");
			writeStringToClient(response, "{success:false,message:'读取文件失败'}", false);
		}
		System.out.println("上传文件名" + fileFileName);
		System.out.println("上传文件类型" + fileContentType);
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				System.out.println("关闭输入流失败");
				e.printStackTrace();
			}
		}
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				System.out.println("关闭输出流失败");
				return;
			}
		}
		writeStringToClient(response, "{success:true,message:'文件上传成功'}", false);
	}

	public void downloadTemplateFile() throws IOException {
		InputStream in = new FileInputStream(ServletActionContext.getServletContext().getRealPath("/templates") + "/importMB.xls");
		OutputStream out = response.getOutputStream();
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("课程表导入模板（单元格必须都是文本格式）.xls", "UTF-8"));
		// 写文件
		int b;
		while ((b = in.read()) != -1) {
			out.write(b);
		}

		in.close();
		out.close();
	}

	public void downloadMajorTemplateFile() throws IOException {
		InputStream in = new FileInputStream(ServletActionContext.getServletContext().getRealPath("/templates") + "/importMajor.xls");
		OutputStream out = response.getOutputStream();
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("专业导入模板（单元格必须都是文本格式）.xls", "UTF-8"));
		// 写文件
		int b;
		while ((b = in.read()) != -1) {
			out.write(b);
		}

		in.close();
		out.close();
	}

	public void downloadUserTemplateFile() throws IOException {
		InputStream in = new FileInputStream(ServletActionContext.getServletContext().getRealPath("/templates") + "/importUser.xls");
		OutputStream out = response.getOutputStream();
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("用户导入模板（单元格必须都是文本格式）.xls", "UTF-8"));
		// 写文件
		int b;
		while ((b = in.read()) != -1) {
			out.write(b);
		}

		in.close();
		out.close();
	}

	public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
		final String userAgent = request.getHeader("USER-AGENT");
		try {
			String finalFileName = null;
			if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
				finalFileName = URLEncoder.encode(fileName, "UTF8");
			} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
				finalFileName = new String(fileName.getBytes(), "UTF8");
			} else {
				finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
			}
			response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");// 这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
		} catch (UnsupportedEncodingException e) {
		}
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getFname() {
		return fname;
	}

	public void setFname(String fname) {
		this.fname = fname;
	}

	public String getFvalue() {
		return fvalue;
	}

	public void setFvalue(String fvalue) {
		this.fvalue = fvalue;
	}

	public Integer getN1() {
		return n1;
	}

	public void setN1(Integer n1) {
		this.n1 = n1;
	}

	public String getS1() {
		return s1;
	}

	public void setS1(String s1) {
		this.s1 = s1;
	}

	public String getInstantClass() {
		return instantClass;
	}

	public void setInstantClass(String instantClass) {
		this.instantClass = instantClass;
	}

	public int[] getDelIds() {
		return delIds;
	}

	public void setDelIds(int[] delIds) {
		this.delIds = delIds;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public String getS2() {
		return s2;
	}

	public void setS2(String s2) {
		this.s2 = s2;
	}

	public boolean isQuery() {
		return query;
	}

	public void setQuery(boolean query) {
		this.query = query;
	}

	public String getQueryField() {
		return queryField;
	}

	public void setQueryField(String queryField) {
		this.queryField = queryField;
	}

	public String getQueryValue() {
		return queryValue;
	}

	public void setQueryValue(String queryValue) {
		this.queryValue = queryValue;
	}

	public String getOverdepartment() {
		return overdepartment;
	}

	public void setOverdepartment(String overdepartment) {
		this.overdepartment = overdepartment;
	}
}
